//
//  PlayingViewController.m
//  Coco_Music
//
//  Created by K。 on 15/6/19.
//  Copyright (c) 2015年 寇广超. All rights reserved.
//

#import "PlayingViewController.h"
#import "ProgressHUD.h"
#import <ShareSDK/ShareSDK.h>
#import "CollectionData.h"
@interface PlayingViewController ()

@property(nonatomic,retain)UIButton *preButton;
@property(nonatomic,retain)UIImageView *backImageView;
@property(nonatomic,retain)UILabel *songNameLabel;
@property(nonatomic,copy)NSString *songName;
@property(nonatomic,copy)NSString *singerName;
@property(nonatomic,copy)NSString *detail;
@property(nonatomic,retain)UITableView *songListTableView;
@property(nonatomic,assign)BOOL isDisPlayList;
@property(nonatomic,assign)NSInteger songLenth;
@property(nonatomic,retain)UILabel *songDetail;
@property(nonatomic,copy)NSString *duration;
@property(nonatomic,retain)UIImageView *backImage;
@property(nonatomic,retain) UIImageView * PlayBackImageView;
@property(nonatomic,retain) Play *play;

@end
@implementation PlayingViewController
+(instancetype)shareHandleController
{  //创建单列对象
   
    static PlayingViewController *playerVC= nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        playerVC = [[PlayingViewController alloc]init];
        playerVC.STKPlayer = [[STKAudioPlayer alloc] init];
        
    });
    
    return playerVC;
    
}
-(void)dealloc
{
    [_imageView release];
    [_preButton release];
    [_backImage release];
    [_PlayBackImageView release];
     [_showView release];
    [super dealloc];

}
- (void)viewDidLoad {
    [super viewDidLoad];
  self.playWithWay = PlayWithWaySole;
    self.view.backgroundColor = [UIColor whiteColor];
    
    [[CollectionData shareCollectionData]openCollectionData];

    
   
    UIImage *image  = [UIImage imageNamed:@"5332974e3dfae93ce7000001"];
    
    self.backImageView = [[UIImageView alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
    self.backImageView.image = [UIImage imageNamed:@"Backimge.png"];
//    self.backImageView.contentMode =UIViewContentModeCenter;
    [self.view addSubview: self.backImageView ];
    
    UIVisualEffectView *visualEfView = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleLight]];
    visualEfView.frame = self.view.frame;
    visualEfView.alpha = 1;
    [self.backImageView  addSubview:visualEfView];
    
  self.imageView = [[UIImageView alloc]initWithFrame:CGRectMake([UIScreen mainScreen].bounds.origin.x+30, [UIScreen mainScreen].bounds.origin.y+64+100, [UIScreen mainScreen].bounds.size.width*0.8, [UIScreen mainScreen].bounds.size.width*0.8)];
    
   self.imageView.image = image;
    self.imageView.center = self.view.center;
    
    [visualEfView addSubview:self.imageView];
    
    self.imageView.layer.masksToBounds = YES;//隐藏边框
    self.imageView.layer.cornerRadius = [UIScreen mainScreen].bounds.size.width*0.8/2;
    //边框宽度
    self.imageView.layer.borderWidth = 2;
    //边框颜色
//    self.imageView.layer.borderColor = [UIColor yellowColor].CGColor;
    
    //***play 按钮
    self.PlayBackImageView = [[ UIImageView alloc] initWithFrame:CGRectMake(self.view.frame.size.width/2-64/2, self.view.frame.size.height-64-10, 64, 64)];
    [self.view addSubview:self.PlayBackImageView];
    self.PlayBackImageView.layer.masksToBounds = YES;
    self.PlayBackImageView.layer.cornerRadius = 35 ;
    
    
#pragma 动画旋转
    CABasicAnimation *monkeyAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    monkeyAnimation.toValue = [NSNumber numberWithFloat:2.0 *M_PI];
    monkeyAnimation.duration = 1.5;
    monkeyAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
    monkeyAnimation.cumulative = NO;
    monkeyAnimation.removedOnCompletion = NO; //No Remove
    
    monkeyAnimation.repeatCount = FLT_MAX;
    [self.PlayBackImageView.layer addAnimation:monkeyAnimation forKey:@"AnimatedKey"];
    self.PlayBackImageView.layer.speed = 0.2;
    self.PlayBackImageView.layer.beginTime = 0.0;
    
 
    
    [self createSubViews];
     [self creatSongList];
    [_imageView release];
    [_backImage release];
    [_PlayBackImageView release];

}
-(void)createSubViews
{
   
    self.showView = [[UIView alloc]initWithFrame:CGRectMake(0, -135, self.view.frame.size.width, 150)];
    _showView.backgroundColor = [UIColor clearColor];
    [self.view addSubview: _showView];
    [_showView release];
    
  
    //**收藏
    self.favorite = [UIButton buttonWithType:UIButtonTypeCustom];
    _favorite.frame = CGRectMake(self.view.frame.size.width/2 + 150,  self.view.frame.size.height * 0.047, 25, 25);
    [_favorite setBackgroundImage:[UIImage imageNamed:@"shoucang副本.png"] forState:UIControlStateNormal];
    [_favorite addTarget:self action:@selector(FavorateButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [_showView addSubview:_favorite];
    
    //**
    self.share = [UIButton buttonWithType:UIButtonTypeCustom];
    [_share setBackgroundImage:[UIImage imageNamed:@"share.png"] forState:UIControlStateNormal];
    _share.frame = CGRectMake(self.view.frame.size.width/2 + 150,  self.view.frame.size.height *0.15, 25, 25);
    [_share addTarget:self action:@selector(ShareButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [_showView addSubview:_share];
    
    _currentPlaybackTime = [[UILabel alloc] initWithFrame:CGRectMake(5,self.view.frame.size.height-64-10 - 35 , 50, 25)];
    _currentPlaybackTime.font =[UIFont boldSystemFontOfSize:14.0f];
    _currentPlaybackTime.textAlignment = NSTextAlignmentCenter;
    _currentPlaybackTime.textColor = [UIColor blackColor];
    _currentPlaybackTime.text = @"00:00";
    [self.view addSubview:_currentPlaybackTime];
    

    progress = [[UISlider alloc]initWithFrame:CGRectMake(_currentPlaybackTime.frame.size.width + _currentPlaybackTime.frame.origin.x,self.view.frame.size.height-64-10 - 20 - 5, self.view.frame.size.width -110, 5)];
    progress.continuous = YES;
    progress.minimumTrackTintColor = [UIColor colorWithRed:244.0f/255.0f green:147.0f/255.0f blue:23.0f/255.0f alpha:1.0f];
    progress.maximumTrackTintColor = [UIColor lightGrayColor];
    [progress addTarget:self action:@selector(PlaySlider) forControlEvents:UIControlEventValueChanged];
    
    
    progress.minimumValue = 0.0;
    progress.maximumValue = 50;
    [progress setThumbImage:[UIImage imageNamed:@"player-progress-point-h"] forState:UIControlStateNormal];
    [self.view addSubview:progress];
    

    _totalPlaybackTime = [[UILabel alloc] initWithFrame:CGRectMake(progress.frame.size.width+progress.frame.origin.x, self.view.frame.size.height-64-10 - 30 - 5 , 50, 25)];
    _totalPlaybackTime.font =[UIFont boldSystemFontOfSize:14.0f];
    _totalPlaybackTime.textAlignment = NSTextAlignmentCenter;
    _totalPlaybackTime.textColor = [UIColor blackColor];
    _totalPlaybackTime.text = @"00:00";
    [self.view addSubview:_totalPlaybackTime];
    
    
    
    _playButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _playButton.frame = CGRectMake(self.view.frame.size.width/2-64/2, self.view.frame.size.height-64-10, 64, 64);
    [_playButton setImage:[UIImage imageNamed:@"play.png"] forState:UIControlStateNormal];
    [_playButton setImage:[UIImage imageNamed:@"playHight.png"] forState:UIControlStateHighlighted];
    [_playButton addTarget:self action:@selector(playButtonEvent) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_playButton];
    
    
    self.preButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.preButton.frame = CGRectMake(_playButton.frame.origin.x-60, _playButton.frame.origin.y+8, 48, 48);
    [self.preButton setImage:[UIImage imageNamed:@"preSong.png"] forState:UIControlStateNormal];
    [self.preButton addTarget:self action:@selector(preButtonEvent) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.preButton];
    [_preButton release];
    
    _nextButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _nextButton.frame = CGRectMake(_playButton.frame.origin.x+70, _playButton.frame.origin.y+8, 48, 48);
    [_nextButton setImage:[UIImage imageNamed:@"nextSong.png"] forState:UIControlStateNormal];
    [_nextButton addTarget:self action:@selector(nextButtonEvent) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_nextButton];
    
    _playbackButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _playbackButton.frame =  CGRectMake(5, _preButton.frame.origin.y, 48, 48);
    [_playbackButton setImage:[UIImage imageNamed:@"order.png"] forState:UIControlStateNormal];
    [_playbackButton addTarget:self action:@selector(playBackButtonEvent) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_playbackButton];
    isPlayBack = 0;
    
    _playListButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _playListButton.frame =  CGRectMake(self.view.frame.size.width-48-5, _preButton.frame.origin.y, 48, 48);
    [_playListButton setImage:[UIImage imageNamed:@"playList.png"] forState:UIControlStateNormal];
    [_playListButton addTarget:self action:@selector(playListButtonEvent) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_playListButton];
    
   
    self.songNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height-64-10 - 50, 150, 20)] ;
    self.songNameLabel.center = CGPointMake(self.view.center.x, 50);
    self.songNameLabel.textAlignment = NSTextAlignmentCenter;
    self.songNameLabel.font = [UIFont systemFontOfSize:20];
    [self.view addSubview:self.songNameLabel];
    

    //***取消渲染
    
    UIImage *image1 = [UIImage imageNamed:@"fanhui.png"];
    image1 = [image1 imageWithRenderingMode: UIImageRenderingModeAlwaysOriginal];
    
    UIImage *image2 = [UIImage imageNamed:@"nav_music@2x.png"];
    image2 = [image2 imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
  
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:image1 style:UIBarButtonItemStylePlain target:self action:@selector(leftButtonAction)];
    
    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc]initWithImage:image2 style:UIBarButtonItemStyleDone target:self action:@selector(rightButtonAction)] autorelease];
    
}


//*** 收藏
-(void)FavorateButtonAction:(UIButton *)btn
{
    
    Play *play = [self.array objectAtIndex:self.number];
    if (play.song_name == nil) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请选首歌后在收藏吧" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alertView show];
    }
    else
    {
    NSMutableArray *array = [[CollectionData shareCollectionData]GetCollection];
    NSMutableArray *arrayjudge = [NSMutableArray array];
    for (Play *play2 in array) {
        [arrayjudge addObject:play2.song_name];
    }
    if ([arrayjudge containsObject:play.song_name] == YES) {
        [self.favorite setBackgroundImage:[UIImage imageNamed:@"yishoucang副本.png"] forState:UIControlStateNormal];
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您已收藏" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [NSTimer scheduledTimerWithTimeInterval:1.5f target:self selector:@selector(dimissAlert:) userInfo:[NSDictionary dictionaryWithObjectsAndKeys:alertView, @"alert2" ,nil] repeats:NO];
        [alertView show];
        
    }else {
        [self.favorite setBackgroundImage:[UIImage imageNamed:@"shoucang副本.png"] forState:UIControlStateNormal];
        [[CollectionData shareCollectionData]insertCollection:play];

        UIAlertView *alertView1 = [[UIAlertView alloc] initWithTitle:@"提示" message:@"已飞入我的收藏" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [NSTimer scheduledTimerWithTimeInterval:1.5f target:self selector:@selector(dimissAlert:) userInfo:[NSDictionary dictionaryWithObjectsAndKeys:alertView1, @"alert3" ,nil] repeats:NO];
        [alertView1 show];
        
    }
    }
}

//** 分享
-(void)ShareButtonAction:(UIButton *)btn
{
    NSLog(@"123132");
    NSString *shareUrl = [NSString stringWithFormat:@"歌手:%@\n歌曲:%@\nurl:%@",self.singerName,self.songName,self.shareUrl];
    //SingDanli * danli = [SingDanli shareInstance];
    NSString *imagePaths = [[NSBundle mainBundle] pathForResource:@"ShareSDK" ofType:@"png"];
    
    //构造分享内容
    id<ISSContent> publishC = [ShareSDK content:shareUrl defaultContent:@"测试一下" image:[ShareSDK imageWithPath:imagePaths] title:@"ShareSDK"  url:@"http://www.mob.com" description:@"这是一条测试信息" mediaType:SSPublishContentMediaTypeNews];
    
    UIView * sender = [[UIView alloc]initWithFrame:CGRectMake(self.view.frame.size.height - 120, 25, self.view.frame.size.width - 50, self.view.frame.size.height * 0.189)];
    UIImageView * view = [[UIImageView alloc]initWithFrame:CGRectMake(self.view.frame.size.height - 120, 25, 50, 50)];
    view.image = [UIImage imageNamed:@"qq.png"];
    [sender addSubview:view];
    [self.view addSubview:sender];
    //创建弹出菜单容器
    id<ISSContainer> container = [ShareSDK container];
    [container setIPadContainerWithView:sender arrowDirect:UIPopoverArrowDirectionUp];
    
    //弹出分享菜单
    [ShareSDK showShareActionSheet:nil shareList:nil content:publishC statusBarTips:YES authOptions:nil shareOptions:nil
    result:^(ShareType type, SSResponseState state, id<ISSPlatformShareInfo> statusInfo, id<ICMErrorInfo> error, BOOL end) {

    if (state == SSResponseStateSuccess)
    {
    self.logiend = YES;
    UIAlertView * view = [[UIAlertView alloc]initWithTitle:@"分享成功" message:nil delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];
    [view show];
    [NSTimer scheduledTimerWithTimeInterval:1.5f target:self selector:@selector(dimissAlert:) userInfo:[NSDictionary dictionaryWithObjectsAndKeys:view, @"alert" ,nil] repeats:NO];
    }
    else if (state == SSResponseStateFail)
    {
    NSLog(NSLocalizedString(@"TEXT_ShARE_FAI", @"分享失败,错误码:%d,错误描述:%@"), [error errorCode], [error errorDescription]);
    }
}];
    


}

-(void)rightButtonAction
{
    [self.navigationItem.rightBarButtonItem setEnabled:NO];
    if (self.fontState == 0) {
        [UIView animateWithDuration:0.5 animations:^{
           self.showView.frame = CGRectMake(0, 63, self.view.frame.size.width, self.view.frame.size.height * 0.284);
        } completion:^(BOOL finished) {
            [self.navigationItem.rightBarButtonItem setEnabled:YES];
        }];
        self.fontState = 1;
    } else {
        [UIView animateWithDuration:0.5 animations:^{
              self.showView.frame = CGRectMake(0, -145, self.view.frame.size.width, self.view.frame.size.height * 0.284);
        } completion:^(BOOL finished) {
            [self.navigationItem.rightBarButtonItem setEnabled:YES];
        }];
        self.fontState = 0;
    }

}

- (void)dimissAlert:(NSTimer *)alert {
    UIAlertView * alert1 = [alert.userInfo objectForKey:@"alert"];
    UIAlertView * alert2 = [alert.userInfo objectForKey:@"alert1"];
    UIAlertView * alert3 = [alert.userInfo objectForKey:@"alert2"];
    
    [alert1 dismissWithClickedButtonIndex:0 animated:YES];
    [alert2 dismissWithClickedButtonIndex:0 animated:YES];
    [alert3 dismissWithClickedButtonIndex:0 animated:YES];
}

#pragma  锁屏调用方法
- (void)playButtonPress:(UIImage *)image {
    if (image == nil) {
        
    }
    else
    {
    Class playingInfoCenter = NSClassFromString(@"MPNowPlayingInfoCenter");
    
    if (playingInfoCenter) {
        
        NSMutableDictionary *songInfo = [ [NSMutableDictionary alloc] init];
        MPMediaItemArtwork *albumArt = [ [MPMediaItemArtwork alloc] initWithImage:image];
        
        [ songInfo setObject: self.songName forKey:MPMediaItemPropertyTitle ];
        [ songInfo setObject: self.singerName forKey:MPMediaItemPropertyArtist ];
        //音乐进度
        songInfo[MPMediaItemPropertyPlaybackDuration] = @(self.STKPlayer.duration);
        
        [ songInfo setObject: albumArt forKey:MPMediaItemPropertyArtwork ];
        [ [MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:songInfo ];
        
    }
    }
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.songListTableView reloadData];
    
}

-(void)creatSongList{
 
    
    self.songListTableView = [[UITableView alloc]initWithFrame:CGRectMake([[UIScreen mainScreen]bounds ].size.width, 0, [[UIScreen mainScreen]bounds ].size.width, [[UIScreen mainScreen]bounds ].size.height) style:UITableViewStylePlain] ;
    self.songListTableView.backgroundColor = [UIColor lightGrayColor];
    self.songListTableView.alpha = 1.0;
    self.songListTableView.delegate = self;
    self.songListTableView.dataSource = self;
    [self.view addSubview:self.songListTableView];
    [self.songListTableView reloadData];
    
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    
    NSString *str = [NSString stringWithFormat:@"播放列表(%ld)",self.array.count];
    return str;
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 50;
}

//点击cell播放对应歌曲
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self musicUrl:indexPath.row];    
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.array.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellIdentifie = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifie];
    if (cell == nil) {
       cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifie];
    }
  
    self.play =  [self.array objectAtIndex:indexPath.row];
    NSString *name = [NSString stringWithFormat:@"%@ -- %@",self.play.singer_name ,self.play.song_name];
  
    cell.layer.transform = CATransform3DMakeScale(0.3, 0.3, 0.1);
    [UIView animateWithDuration:0.5 animations:^{
        
        cell.layer.transform = CATransform3DMakeScale(1, 1, 0.1);
        
    }];
    
    cell.textLabel.text = name;
    cell.textLabel.font = [UIFont systemFontOfSize:14.0];
    cell.tintColor= [UIColor colorWithRed:244.0f/255.0f green:147.0f/255.0f blue:23.0f/255.0f alpha:1.0f];
    return cell;
}


-(void)setNSTimer
{
    self.mytime = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(buttonAction) userInfo:nil repeats:YES];
    
    [[NSRunLoop currentRunLoop] addTimer:self.mytime forMode:NSRunLoopCommonModes];
}

-(void)PlaySlider
{
    if (!self.STKPlayer) {
        return;
    }
    [self.STKPlayer seekToTime:progress.value];
}

-(void)playButtonEvent
{
    if (!self.STKPlayer)
    {
        return;
    }
    if (isPlaying) {
        isPlaying = NO;
    }else{
        isPlaying = YES;
    }
    
    NSLog(@"%u",self.STKPlayer.state);
    if (self.STKPlayer.state == STKAudioPlayerStatePaused )
    {
        
        [self.STKPlayer resume];
        
        self.PlayBackImageView.layer.speed = 0.2;
        CFTimeInterval pausedTime = [self.PlayBackImageView.layer timeOffset];
        CFTimeInterval timeSincePause = [self.PlayBackImageView.layer convertTime:CACurrentMediaTime() fromLayer:nil] - pausedTime;
        self.PlayBackImageView.layer.beginTime = timeSincePause;
    }
    else
    {
        [self.STKPlayer pause];
        
        [self.mytime invalidate];
        CFTimeInterval pausedTime = [self.PlayBackImageView.layer convertTime:CACurrentMediaTime() fromLayer:nil];
        self.PlayBackImageView.layer.speed = 0.0;
        self.PlayBackImageView.layer.timeOffset = pausedTime;
        [self.mytime invalidate];
    }
    
    [_playButton setImage:isPlaying?[UIImage imageNamed:@"play.png"]:[UIImage imageNamed:@"pasue.png"] forState:UIControlStateNormal];
    [_playButton setImage:isPlaying?[UIImage imageNamed:@"pasueHight.png"]:[UIImage imageNamed:@"playHight.png"] forState:UIControlStateHighlighted];
}


#pragma 上一曲
-(void)preButtonEvent
{
   
    if (self.number < 1) {
        UIAlertView *alrt = [[UIAlertView alloc] initWithTitle:@"哎呦" message:@"这是第一首" delegate:self cancelButtonTitle:nil otherButtonTitles:@"好", nil];
        [alrt show];
        return;
    }
    if (self.playWithWay == PlayWithWaySole) {//如果为顺序循环播放
        if (self.STKPlayer.state == STKAudioPlayerStatePlaying) {
            [self musicUrl:--self.number];
            
        }
    }if (self.playWithWay == PlayWithWayRandom){

        if (self.STKPlayer.state == STKAudioPlayerStatePlaying) {
            self.number = arc4random() % self.array.count;
           
            [self musicUrl:self.number];
        }
        
    }if (self.playWithWay == PlayWithWayOneSongCirculation){
        if (self.STKPlayer.state == STKAudioPlayerStatePlaying) {
             [self musicUrl:--self.number];
        }
    }
}

//** 循环
-(void)playBackButtonEvent
{
    if (_playWithWay == PlayWithWayOneSongCirculation) {//单曲循环播放
        [_playbackButton setImage:[UIImage imageNamed: @"random.png"] forState:UIControlStateNormal];
        [ProgressHUD showSuccess:@"随机播放"];
        
        _playWithWay = PlayWithWayRandom;
        return;
    }
    if (_playWithWay == PlayWithWayRandom){//随机播放
        [_playbackButton setImage:[UIImage imageNamed:@"order.png"] forState:UIControlStateNormal];
        _playWithWay = PlayWithWaySole;
        [ProgressHUD showSuccess:@"顺序播放"];
        return;
        
    }
    else{//顺序循环
        [_playbackButton setImage:[UIImage imageNamed:@"lock.png"] forState:UIControlStateNormal];
        _playWithWay = PlayWithWayOneSongCirculation;
        [ProgressHUD showSuccess:@"单曲播放"];
        return;
    }
}

#pragma 下一曲
-(void)nextButtonEvent
{ if (self.playWithWay == PlayWithWaySole) {//如果为顺序循环播放
    if (self.STKPlayer.state == STKAudioPlayerStatePlaying) {
        if (self.number == self.array.count - 1) {
            self.number = 0;
            [self musicUrl:self.number];
            return;
        }
        [self musicUrl:++self.number];
      
    }
}
    if (self.playWithWay == PlayWithWayRandom){
    if (self.STKPlayer.state == STKAudioPlayerStatePlaying) {
        self.number = arc4random() % self.array.count;
        
        [self musicUrl:self.number];
    }
    
}
    if (self.playWithWay == PlayWithWayOneSongCirculation){
    if (self.STKPlayer.state == STKAudioPlayerStatePlaying) {
          [self musicUrl:++self.number];
        
    }
    
}
}
//***播放列表

-(void)playListButtonEvent
{
    
    if (self.isDisPlayList) {
        [UIView animateWithDuration:0.5 animations:^{
            
            self.songListTableView.alpha = 1.0;
                  self.songListTableView.frame = CGRectMake( [[UIScreen mainScreen]bounds ].size.width, 0, [[UIScreen mainScreen]bounds ].size.width, [[UIScreen mainScreen]bounds ].size.height);
            [self.view bringSubviewToFront:self.songListTableView];
        }];
        self.isDisPlayList = NO;
    }else{
    
      [UIView animateWithDuration:0.5 animations:^{
          
          self.songListTableView.alpha = 0.7;
    
          self.songListTableView.frame = CGRectMake([[UIScreen mainScreen]bounds ].origin.x,[[UIScreen mainScreen]bounds ].origin.y + 100, [[UIScreen mainScreen]bounds ].size.width, [[UIScreen mainScreen]bounds ].size.height - 300);
          self.songListTableView.center = self.view.center;

      }];
        self.isDisPlayList = YES;
    }
}



#pragma slider触发方法
-(void)buttonAction{

    if (!self.STKPlayer) {
        return;
    }
    progress.value = self.STKPlayer.progress;
    progress.maximumValue = self.STKPlayer.duration;
    
    if (self.STKPlayer.duration - progress.value < 2) {
        if (self.playWithWay == PlayWithWayOneSongCirculation && self.STKPlayer.duration != 0) {
            [self musicUrl:self.number];
          
        }
        else
        {
        [self nextButtonEvent];
        }
    }
    
    NSInteger minutes  = (NSInteger)self.STKPlayer.duration / 60;
    NSInteger seconds = (NSInteger)self.STKPlayer.duration % 60;
    NSString *string = [NSString stringWithFormat:@"%02ld:%02ld",minutes,seconds];
    
    _totalPlaybackTime.text =string;
    _totalPlaybackTime.tintColor = [UIColor colorWithRed:244.0f/255.0f green:147.0f/255.0f blue:23.0f/255.0f alpha:1.0f];
    
    NSInteger currentminutes = (NSInteger)self.STKPlayer.progress / 60;
    NSInteger currentseconds = (NSInteger)self.STKPlayer.progress % 60;
    NSString *string1 = [NSString stringWithFormat:@"%02ld:%02ld",currentminutes,currentseconds];
    
   _currentPlaybackTime.text =string1;
   _currentPlaybackTime.tintColor = [UIColor colorWithRed:244.0f/255.0f green:147.0f/255.0f blue:23.0f/255.0f alpha:1.0f];
    
    [_playButton setImage:[UIImage imageNamed:@"pasue.png"] forState:UIControlStateNormal];
    
    //歌单自动滚到播放的对应的歌曲


}

-(void)setIndexPath:(NSInteger)indexPath
{
    self.number = indexPath;
    [self musicUrl:self.number];
}

-(void)musicUrl:(NSInteger)number
{
   self.play  = [self.array objectAtIndex:number];
#pragma 取音乐品质
    if (self.play.audition_list.count == 1) {
          NSMutableDictionary *dic = [self.play.audition_list firstObject];
        NSString *temp = [dic objectForKey:@"url"];
        self.shareUrl = temp;
        self.singerName = self.play.singer_name;
        self.songName = self.play.song_name;
        self.detail = [NSString stringWithFormat:@"%@ -- %@",self.singerName ,self.songName];
        self.navigationItem.title = self.detail;
        [self getNetPic:self.play.singer_name];
        [self playMusic:temp];

    }else{
        NSMutableDictionary *dic = [self.play.audition_list objectAtIndex:1];
        NSString *temp = [dic objectForKey:@"url"];
        self.shareUrl = temp;
         NSLog(@"self.shareUrl%@",self.shareUrl);
        self.singerName = self.play.singer_name;
        self.songName = self.play.song_name;
        self.detail = [NSString stringWithFormat:@"%@ -- %@",self.singerName ,self.songName];
        self.navigationItem.title = self.detail;
        [self getNetPic:self.play.singer_name];
        [self playMusic:temp];
    }
    
    [self.songListTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:number inSection:0]
                                        animated:YES
                                  scrollPosition:UITableViewScrollPositionBottom];
    [self.songListTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:number - 3 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];

}

-(void)playMusic:(NSString *)string
{
    [self.STKPlayer playURL:[NSURL URLWithString:string]];
    [self setNSTimer];
}


-(void)StopSTKPlayer
{
    if (self.STKPlayer) {
        [self.STKPlayer stop];
        [_STKPlayer release];
        self.STKPlayer = nil;
        self.mytime = nil;
        progress.value = 0;
    }

}
-(void)getNetPic:(NSString *)name{
    //拼接请求网址
    NSString *urlString= [NSString stringWithFormat:@"%@",name];
    
    NSString * encodedString = (NSString *)CFURLCreateStringByAddingPercentEscapes( kCFAllocatorDefault, (CFStringRef)urlString, NULL, NULL,  kCFStringEncodingUTF8 );
    
    NSString * add1 = @"http://api.raventech.cn/api/music/search?album_name=&appkey=54679361&appversion=ios1.3.0&cate_type=0&client_time=2015-05-21%2015%3A28%3A39&content=";
    NSString *add2 =  @"&deviceid=86D47CC5-7337-4186-98C3-6EB77C5C8CD3&deviceusername=%25E5%25A4%25AA%25E9%2598%25B3&key=";
    NSString *str3 =  @"&network_type=1&page=1&searchtype=0&singer_name=&song_name=&type=0&zone=Asia%252FShanghai%2520%2528GMT%252B8%2529";
    NSString *superAddress = [NSString stringWithFormat:@"%@%@%@%@%@", add1,encodedString,add2,encodedString,str3];
    
    //请求网络数据
    [AFN_block NSString:superAddress Blokc:^(id request) {
        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:request];
        //  NSLog(@"NSMutableDictionary = %@",dic);
 
        NSMutableDictionary *dic1 = [dic  objectForKey:@"info"];
        NSMutableArray *array = [dic1 objectForKey:@"data"];
        if (array.count == 0) {
            self.imageView.image = [UIImage imageNamed:@"NoPlaying"];
            return ;
        }
        NSMutableDictionary *dic2 = [array objectAtIndex:0];
        
        //设置歌手图片转盘旋转
        NSString *str = [dic2 objectForKey:@"pic_url"];
        NSURL *url = [NSURL URLWithString:str];
        
        //***毛玻璃背景图片
        [self.backImageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"Backimge.png"]];
        //***中间按钮背景图片
        [self.imageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"5332974e3dfae93ce7000001"]];
        //***播放按钮背景图片
        [self.PlayBackImageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"5332974e3dfae93ce7000001"]];
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
         NSData *data = [NSData dataWithContentsOfURL:url];
            UIImage *image = [UIImage imageWithData:data];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self playButtonPress:image];
            });
        });
    }];
}


-(void)leftButtonAction
{
     [self dismissViewControllerAnimated:YES completion:^{
         
         
     }];
   
}

-(void)BackHome
{
    [self dismissViewControllerAnimated:YES completion:^{
        
        
    }];
    
    
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
